<template>
  <div ref="mgrDialog" class="dialog-wrap">
    <el-dialog :title="title" width="50%" :visible.sync="DialogVisible" @close="dialogClose">
      <el-row :gutter="20">
        <el-form
            ref="editForm"
          v-if="editForm != null"
          size="mini"
          :label-width="formLabelWidth"
          :rules="rules"
          :model.sync="editForm"
        >
          <el-col :span="12">
            <el-form-item label="分类名称" :label-width="formLabelWidth" prop="name">
              <el-input v-model="editForm.name" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
    
          <el-col :span="12">
            <el-form-item label="选择父类" :label-width="formLabelWidth">
              <el-select v-model="editForm.parentId" placeholder="请选择">
                <el-option
                  v-for="item in gserviceCata"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  :disabled="disabled(item)"
                  :style="{'text-indent': item.step == 1 ? 0 : (item.step == 2 ? '20px' : '40px') }"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        <el-col :span="12">
            <el-form-item label="选择类型" :label-width="formLabelWidth">
                <el-select multiple v-model="editForm.typeId" placeholder="请选择">
                    <el-option
                        v-for="item in typeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-col>
          <el-col :span="12">
            <el-form-item label="排序" :label-width="formLabelWidth">
              <el-input v-model="editForm.cateSeq" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
						<el-form-item label="分类图标" :label-width="formLabelWidth">
		      				
							<!-- 添加图片按钮 -->
							<div 
								v-if="!editForm.icon" 
								class="icon-wrap" 
								@click="uploadClick">
								<i class="el-icon-circle-plus-outline"
								></i>
							</div>
							
              <div class="imgBox" v-if="editForm.icon" @click="editForm.icon=''">
                  <el-image
                      
                      style="width: 50px;height: 50px;"
                      :src="imgPrefix+editForm.icon"
                      fit="scale-down"
                      @click.native="uploadClick"
                  ></el-image>
                  <div class="imgLight el-icon-close"></div>
              </div>

							<el-upload
            					ref="iconUpload"
								with-credentials
							  	:action="uploadUrl"
							  	style="display: none"
							  	accept="image/*"
							  	:headers="uploadHeaders"
							  	:on-change="handleUploadChange"
							>
					  			<el-button size="small" id="uploadImg" ref="uploadImg">点击上传</el-button> 
							</el-upload>

		    			</el-form-item>
		    		</el-col>

        </el-form>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="confirm">{{ confirmText }}</el-button>
        <el-button size="mini" type="danger" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { getToken } from "@/utils/auth";
import { getList } from "@/api/admin/gservice";
import { baseUrl } from "@/config/env";
import { list } from "@/api/agri-product/goodsType";

//上传图片的url
const uploadUrl = baseUrl + "/rest/common/upload";
//获取图片的url
const imgPrefix = baseUrl + "/rest/common/preview/";

export default {
  props: {
    title: {
      type: String,
      default: "编辑"
    },
    type: {
      type: [Number, String],
      default: 1
    },
    visible: {
      type: Boolean,
      default: false
    },
    form: {
      type: Object,
      default: null
    }
  },
  computed: {},
  watch: {
    form(newVal, oldVal) {
      if (newVal != null) {
        this.editForm = newVal;
        console.log(this.editForm.typeId);
        if(this.editForm.typeId){
             this.editForm.typeId = newVal.typeId.split(',')
        }
      } else {
        this.editForm = Object.assign({}, this.defaultForm);
      }
    },
    type(newVal, oldVal) {
      if (newVal == 1) {
        this.confirmText = "新增";
        this.editForm = Object.assign({}, this.defaultForm);
      } else if (newVal == 2) {
        this.confirmText = "修改";
        //this.editForm = this.form;
      }
    },
    visible(val) {
      this.DialogVisible = val;

      //每次打开时刷新分类数据
      if (val) {
        this.getGserviceList();
      }

      if (this.type == 1) {
        this.editForm = Object.assign({}, this.defaultForm);
      } else if (this.type == 2) {
        this.editForm = this.form;
      }
    }
  },
  data() {
    return {
        rules: {
            name :[{required: true, message: '请输入分类名称', trigger: 'blur'}]
        },
      gserviceCata: [],
      editForm: {
        name: "",
        parentId: "",
        icon: "",
        cateSeq: 0
      },
      defaultForm: {
        name: "",
        parentId: "",
        icon: "",
        cateSeq: 0
      },
      imgPrefix: imgPrefix,
      uploadUrl: uploadUrl,
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      DialogVisible: false,
      formLabelWidth: "100px",
      confirmText: "修改",
      typeList: [], // 类型集合
    };
  },
  created () {
      this.getGserviceList();
      this.getTypeList()
  },
  mounted() {
    //this.init();
    // this.getGserviceList();
  },
  methods: {
    init() {
      if (this.type == 1) {
        //新增
        this.confirmText = "新增";
        this.editForm = Object.assign({}, this.defaultForm);
      } else if (this.type == 2) {
        //编辑
        this.confirmText = "修改";
        this.editForm = this.form;
      }
    },
    getGserviceList() {
        this.gserviceCata = [];
      getList(1, 999).then(res => {
        // var result = res.data.data;
        // this.gserviceCata = result.records;
        this.add(res.data.data.records)
      });
    },
    getTypeList() {
        this.typeList = [];
        list(1, 999).then(res => {
            var result = res.data.data;
            this.typeList = result.records;
        });
    },
    add(data) {
    //     data.forEach(item => {
    //         this.gserviceCata.push({
    //             name: item.name,
    //             id: item.id,
    //             parentId: item.parentId,
    //             step: step
    //         });
    //         item.children.length && this.add(item.children);
    //    })

       data.forEach(item => {
            this.gserviceCata.push({
                name: item.name,
                id: item.id,
                parentId: item.parentId,
                step: 1
            });
            if (item.children.length) {
                item.children.forEach(items => {
                    this.gserviceCata.push({
                        name: items.name,
                        id: items.id,
                        parentId: items.parentId,
                        step: 2
                    }); 

                    if (items.children.length) {
                        items.children.forEach(itemC => {
                            this.gserviceCata.push({
                                name: itemC.name,
                                id: itemC.id,
                                parentId: itemC.parentId,
                                step: 3
                            }); 
                        })
                        
                    }
                })
            }
       })
    },
    disabled (data) {
        if (this.type === 1) {
            return data.step < 3 ? false : true;
        }
        else {
            let index;
            this.gserviceCata.forEach(item => {
                if (item.id === this.form.id) {
                    index = item.step;
                }
            })
            console.log(this.gserviceCata, index, 'index')
            return index === 1 ? true : (index - data.step > 0 ? false : true)
        }
        
    },
    //取消按钮
    cancel() {
      this.$emit("btnCancel");
      this.editForm = Object.assign({}, this.defaultForm);
      this.DialogVisible = false;
    },
    confirm() {
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            this.editForm.typeId = this.editForm.typeId.toString()
            this.$emit("btnConfirm", this.type, this.editForm);
            this.editForm = null;
            this.DialogVisible = false;
          } else {
            return false;
          }
        });
    },
    dialogClose() {
      this.cancel();
    },
    //打开图片上传
    uploadClick() {
      var uploadBtn = window.document.getElementById("uploadImg");
      uploadBtn.click();
    },
    //文件状态改变
    handleUploadChange(file, fileList) {
      console.log("------文件状态改变------");
      console.log(file, fileList);
      if (file.status == "success") {
        console.log("------上传成功-----");
        
        this.editForm.icon = file.response.data.fileId;
        console.log(this.editForm.icon, '0000');
      }
    }
  },

};
</script>

<style lang="scss" scoped>
.icon-wrap {
  width: 50px;
  height: 50px;
  text-align: center;
  border-radius: 5px;
  background-color: #666666;
  i {
    color: #ffffff;
    font-size: 30px;
    line-height: 50px;
  }
}
.imgBox {
    position: relative;
    width: 50px;
    height: 50px;
    cursor: pointer;
    .imgLight {
        position: absolute;
        width: 50px;
        height: 50px;
        left: 0;
        top: 0;
        background: #000;
        font-size: 50px;
        opacity: 0;
        transition: opacity .3s;
    }
}
.imgBox:hover .imgLight {
    opacity: .5;
}

</style>